package com.flycms.modules.news.service.impl;
import com.flycms.common.pager.Pager;
import com.flycms.common.utils.mark.SnowFlakeUtils;
import com.flycms.common.utils.result.LayResult;
import com.flycms.common.utils.result.Result;
import com.flycms.common.utils.text.Convert;
import com.flycms.modules.company.entity.Company;
import com.flycms.modules.company.service.CompanyService;
import com.flycms.modules.news.dao.NewsDao;
import com.flycms.modules.news.entity.News;
import com.flycms.modules.news.entity.NewsVO;
import com.flycms.modules.news.service.NewsService;
import com.flycms.modules.picture.entity.Picture;
import com.flycms.modules.picture.entity.PictureInfo;
import com.flycms.modules.picture.service.PictureService;
import com.flycms.modules.shiro.ShiroUtils;
import com.flycms.modules.site.entity.ContentVO;
import com.flycms.modules.site.entity.Site;
import com.flycms.modules.site.entity.UserSiteVO;
import com.flycms.modules.site.service.SiteCompanyService;
import com.flycms.modules.site.service.SiteService;
import com.flycms.modules.user.entity.User;
import com.flycms.modules.user.service.UserService;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Biz-Boot, All rights reserved
 * 版权：企业之家网 -- 企业建站管理系统<br/>
 * 开发公司：97560.com<br/>
 *
 * 新闻、图文相关 服务层
 *
 * @author sun-kaifei
 * @version 1.0 <br/>
 * @email 79678111@qq.com
 * @Date: 10:08 2019/6/9
 */

@Service
public class NewsServiceImpl implements NewsService {
    @Autowired
    private SiteCompanyService siteCompanyService;
    @Autowired
    private NewsDao newsDao;
    @Autowired
    private PictureService pictureService;
    @Autowired
    private UserService userService;
    @Autowired
    private SiteService siteService;

    // ///////////////////////////////
    // /////       增加       ////////
    // ///////////////////////////////
    @Transactional
    public Object addUserNews(News news, Long companyId, Integer typeId){
        if(this.checkNewsByTitle(news.getSiteId(),news.getTitle(),null)){
            return Result.failure("您已发布过同类名称文章了");
        }
        news.setId(SnowFlakeUtils.nextId());
        //分析内容中图片，本地图片统计使用次数，远程图片下载并统计使用次数
        news.setContent(pictureService.replaceContent(news.getContent(),companyId,typeId,news.getId()));
        //文章发布人
        news.setUserId(ShiroUtils.getLoginUser().getId());
        news.setCreateTime(LocalDateTime.now());
       int success=newsDao.save(news);
        if(success > 0){
            if(!StringUtils.isEmpty(news.getTitlepic())){
                String fileName=com.flycms.common.utils.StringUtils.getFileName(news.getTitlepic());
                Picture picture=pictureService.findPictureBySignature(companyId,fileName);
                if(!pictureService.checkPictureByInfoId(picture.getId(),news.getId())){
                    PictureInfo info= new PictureInfo();
                    info.setTypeId(typeId);
                    info.setPictureId(picture.getId());
                    info.setInfoId(news.getId());
                    pictureService.savePictureInfo(info);
                }
                int total=pictureService.queryPictureByInfoTotal(companyId,fileName);
                pictureService.updatePictureInfoCount(total,picture.getId());
            }
        }
        return Result.success();
    }

    // ///////////////////////////////
    // /////        刪除      ////////
    // ///////////////////////////////

    /**
     * 批量删除内容
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteNewsByIds(String ids){
        Long[] newsIds = Convert.toLongArray(ids);
        for (Long newsId : newsIds)
        {
            News news = newsDao.findById(newsId);
            if (!siteCompanyService.checkSiteCompany(news.getSiteId())){
                return Result.failure(String.format(news.getTitle()+"%1$s没有操作权限,不能删除"));
            }
        }
        int totalCount=newsDao.deleteNewsByIds(newsIds);
        if(totalCount > 0) {
            return Result.success();
        }else{
            return Result.failure("删除失败");
        }
    }
    // ///////////////////////////////
    // /////        修改      ////////
    // ///////////////////////////////

    /**
     * 修改文章信息
     *
     * @param news
     * @return
     */
    @Transactional
    public Object updateUserNewsById(News news){
        if(this.checkNewsByTitle(news.getSiteId(),news.getTitle(),news.getId())){
            return Result.failure("文章重名了");
        }
        news.setUpdateTime(LocalDateTime.now());
        newsDao.update(news);
        return Result.success();
    }

    // ///////////////////////////////
    // /////        查詢      ////////
    // ///////////////////////////////
    /**
     * 按网站id查询该网站下是否有同标题文章
     *
     * @param siteId
     *         网站id
     * @param title
     *         文章标题
     * @param id
     *         需要排除id
     * @return
     */
    public boolean checkNewsByTitle(Long siteId,String title,Long id) {
        int totalCount = newsDao.checkNewsByTitle(siteId,title,id);
        return totalCount > 0 ? true : false;
    }

    /**
     * 按id查询文章内容
     *
     * @param id
     * @return
     */
    public News findById(Long id){
        return newsDao.findById(id);
    }

    /**
     * 基于layui的资讯翻页列表
     *
     * @param news
     * @param page
     * @param pageSize
     * @param sort
     * @param order
     * @return
     */
    public Object selectNewsListLayPager(News news, Integer page, Integer pageSize, String sort, String order) {
        StringBuffer whereStr = new StringBuffer(" 1 = 1");
        if (!StringUtils.isEmpty(news.getTitle())) {
            whereStr.append(" and title like concat('%',#{entity.title},'%')");
        }
        if (!StringUtils.isEmpty(news.getColumnId())) {
            whereStr.append(" and column_id = #{entity.columnId}");
        }
        whereStr.append(" and deleted = 0");
        whereStr.append(" and site_id = #{entity.siteId}");
        Pager<News> pager = new Pager(page, pageSize);
        //排序设置
        if (!StringUtils.isEmpty(sort)) {
            Boolean rank = "desc".equals(order) ? true : false;
            pager.addOrderProperty(sort, rank,true);
        }
        //使用limit进行查询翻页
        pager.addLimitProperty(true);
        //查询条件
        News entity = new News();
        entity.setTitle(news.getTitle());
        entity.setSiteId(news.getSiteId());
        entity.setColumnId(news.getColumnId());
        pager.setEntity(entity);
        pager.setWhereStr(whereStr.toString());
        List<News> sitelsit = newsDao.queryList(pager);
        List<ContentVO> volsit = new ArrayList<ContentVO>();
        sitelsit.forEach(bean -> {
            ContentVO vo=new ContentVO();
            vo.setId(bean.getId().toString());
            vo.setTitle(bean.getTitle());
            vo.setModuleType("news");
            vo.setCreateTime(bean.getCreateTime());
            volsit.add(vo);
        });
        return LayResult.success(0, "true", newsDao.queryTotal(pager), volsit);
    }

    /**
     * 管理后台基于layui的资讯翻页查询列表
     *
     * @param news
     * @param page
     * @param pageSize
     * @param sort
     * @param order
     * @return
     */
    public Object selectAdminNewsListLayPager(News news, Integer page, Integer pageSize, String sort, String order) {
        //javabean 映射工具
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        MapperFacade mapper = mapperFactory.getMapperFacade();

        StringBuffer whereStr = new StringBuffer(" 1 = 1");
        if (!StringUtils.isEmpty(news.getTitle())) {
            whereStr.append(" and title like concat('%',#{entity.title},'%')");
        }
        if (!StringUtils.isEmpty(news.getColumnId())) {
            whereStr.append(" and column_id = #{entity.columnId}");
        }
        whereStr.append(" and deleted = 0");
        if (!StringUtils.isEmpty(news.getSiteId())) {
            whereStr.append(" and site_id = #{entity.siteId}");
        }
        Pager<News> pager = new Pager(page, pageSize);
        //排序设置
        if (!StringUtils.isEmpty(sort)) {
            Boolean rank = "desc".equals(order) ? true : false;
            pager.addOrderProperty(sort, rank,true);
        }
        //使用limit进行查询翻页
        pager.addLimitProperty(true);
        //查询条件
        News entity = new News();
        entity.setTitle(news.getTitle());
        entity.setSiteId(news.getSiteId());
        entity.setColumnId(news.getColumnId());
        pager.setEntity(entity);
        pager.setWhereStr(whereStr.toString());

        List<NewsVO> volsit = mapper.mapAsList(newsDao.queryList(pager),NewsVO.class);
        volsit.forEach(bean -> {
            User user=userService.findById(bean.getUserId());
            if(user!=null){
                bean.setNickname(user.getNickname());
            }
            Site site=siteService.findById(bean.getSiteId());
            if(site!=null){
                bean.setSiteName(site.getSiteName());
            }
        });
        return LayResult.success(0, "true", newsDao.queryTotal(pager), volsit);
    }

    @Cacheable(value = "news", key ="#news.siteId")
    public Pager<NewsVO> selectNewsListPager(News news, Integer page, Integer pageSize, String sort, String order) {
        //javabean 映射工具
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        MapperFacade mapper = mapperFactory.getMapperFacade();

        StringBuffer whereStr = new StringBuffer(" 1 = 1");
        if (!StringUtils.isEmpty(news.getTitle())) {
            whereStr.append(" and title like concat('%',#{entity.title},'%')");
        }
        if (!StringUtils.isEmpty(news.getColumnId())) {
            whereStr.append(" and column_id = #{entity.columnId}");
        }
        whereStr.append(" and deleted = 0");
        whereStr.append(" and site_id = #{entity.siteId}");
        Pager<NewsVO> pager = new Pager(page, pageSize);
        //排序设置
        if (!StringUtils.isEmpty(sort)) {
            Boolean rank = "desc".equals(order) ? true : false;
            pager.addOrderProperty(sort, rank,true);
        }else{
            pager.addOrderProperty("id", true,true);
        }
        //使用limit进行查询翻页
        pager.addLimitProperty(true);
        //查询条件
        News entity = new News();
        entity.setTitle(news.getTitle());
        entity.setSiteId(news.getSiteId());
        entity.setColumnId(news.getColumnId());
        pager.setEntity(entity);
        pager.setWhereStr(whereStr.toString());
        List<News> sitelsit = newsDao.queryList(pager);
        /*List<ContentVO> volsit = new ArrayList<ContentVO>();
        sitelsit.forEach(bean -> {
            ContentVO vo=new ContentVO();
            vo.setId(bean.getId().toString());
            vo.setTitle(bean.getTitle());
            vo.setModuleType("news");
            vo.setAddTime(bean.getAddTime());
            volsit.add(vo);
        });*/
        pager.setTotal(newsDao.queryTotal(pager));
        List<NewsVO> volsit = mapper.mapAsList(sitelsit,NewsVO.class);
        pager.setList(volsit);
        return pager;
    }
}
